package persistentie;

import domein.Land;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.swing.tree.DefaultMutableTreeNode;

public class LandenMapper extends Mapper<Land>{
	private static final String querySelectLanden = "SELECT * FROM landen WHERE continent = ";

	public Map<String, Land> read(String index) throws SQLException, IllegalStateException, ClassNotFoundException {
		Connectie connectie = new Connectie();
		Map<String, Land> map = new HashMap<String, Land>();
		ResultSet resultSet;

		try 
		{
			resultSet = connectie.executeQuery(querySelectLanden + index);

			while (resultSet.next()) 
			{
				String codeLand = resultSet.getString("codeLand");
				String naamLand = resultSet.getString("naamLand");
				
				Land land = new Land(codeLand, naamLand);
				map.put(naamLand, land);
			}

		}
		catch (Exception e) 
		{
			e.printStackTrace();
			System.out.print("error");
		}

		connectie.closeConnection();

		return map;
	}
	
	public int findContinent(String naamContinent)  throws SQLException{
	Connectie connectie = new Connectie();
	ResultSet resultSet;
	int id = 999;
	System.out.println(naamContinent);
	try 
	{
		resultSet = connectie.executeQuery("SELECT * FROM continenten WHERE naamContinent Like '" + naamContinent + "'");

		while (resultSet.next()) 
		{
			id = resultSet.getInt("idContinent");
		}

	}
	catch (Exception e) 
	{
		e.printStackTrace();
		System.out.print("error");
	}

	connectie.closeConnection();

	return id;
}
	
	public void schrijf(DefaultMutableTreeNode parent,String naamLand, String codeLand) throws SQLException, ClassNotFoundException, SQLException, ClassNotFoundException{
		
		Connectie connectie = new Connectie();
		Connection conn = connectie.getConnection();
		Statement statement = conn.createStatement();
		String sql;     
		
		sql = "INSERT INTO landen (codeLand,naamLand,continent) VALUES ('" + codeLand + "','" +  naamLand + "','" + findContinent(parent.toString()) + "')";
	
		     
		try 
		{
			statement.executeUpdate(sql);
			
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			System.out.print("error");
		}
		
		connectie.closeConnection();
		
	}


}